<template>
  <div class="login-container">
    <van-nav-bar class="page-nav-bar" left-arrow title="登录" @click-left="$router.back()" />
    <van-form ref="loginForm" @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        name="mobile"
        placeholder="手机号"
        :rules="userRules.mobile"
        type="number"
        maxlength="11"
      >
        <i slot="left-icon" class="iconfont icon-shouji" />
      </van-field>
      <van-field
        v-model="user.code"
        name="code"
        :rules="userRules.code"
        placeholder="验证码"
        type="number"
        maxlength="6"
      >
        <i slot="left-icon" class="iconfont icon-yanzhengma" />
        <template #button>
          <van-count-down v-if="showCount" :time="1000*60" format="ss s后再次发送" @finish="showCount=false" />
          <van-button v-else class="sendSms" round size="small" type="default" native-type="button" @click="sendSms">发送验证码</van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { login, sendSms } from '@/api/user'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data() {
    return {
      showCount: false,
      user: {
        mobile: '',
        code: ''
      },
      userRules: {
        mobile: [{
          required: true, message: '请输入手机号', trigger: 'onBlur'
        }, {
          required: true, message: '手机号格式错误', trigger: 'onBlur', pattern: /^1[3|5|7|9]\d{9}$/
        }],
        code: [{
          required: true, message: '请输入验证码', trigger: 'onBlur'
        }]
      }
    }
  },
  methods: {
    ...mapMutations('user', ['setUser']),
    async onSubmit() {
      this.$toast.loading({
        message: '登录中...',
        forbidClick: true,
        duration: 0// 设置为0一直提示 直到下一个toast覆盖
      })
      try {
        const res = await login(this.user)
        this.$toast.success('登录成功')
        // 保存token
        this.setUser(res.data.data)
        // 跳转会原来页面
        this.$router.back()
      } catch (err) {
        this.$toast.fail(err.message)
      }
    },
    async sendSms() {
      // 只校验手机号
      try {
        await this.$refs.loginForm.validate('mobile')
      } catch (err) {
        return console.log(err)
      }
      // 校验通过显示倒计时
      this.showCount = true
      // 发送请求
      try {
        await sendSms(this.user.mobile)
        this.$toast.success('发送成功')
      } catch (err) {
        this.$toast.fail(err.message)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.login-container{
  .iconfont{
    font-size: 32px;
        display: inline-block;
    margin-top: 4px;
  }
  .sendSms{
    height: 45px;
    font-size: 12px;
  }
}
</style>
